package com.smalls.newvideotwo.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings.System;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.smalls.newvideotwo.Constants;
import com.smalls.newvideotwo.NewDTVApp;
import com.smalls.newvideotwo.R;
import com.smalls.newvideotwo.mvp.bean.MovieDetail;
import com.smalls.newvideotwo.mvp.bean.PhotoInfo;
import com.smalls.newvideotwo.view.LiveLoadingDialog;
import com.smalls.newvideotwo.view.SearchLoadingDialog;
import com.smalls.newvideotwo.view.ToastDialog;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
    private static LiveLoadingDialog Loadingdialog = null;
    private static SearchLoadingDialog Loadingserachlog = null;
    private static String TAG = Constant.baddcoolio2tag? Constant.TAGPREFIXSTR + "Utils":"Utils";
    private static List<Activity> mList = new ArrayList();
    private static String mtext = "";
    private static Dialog reg_fail;
    private static long start = 0;
    private static String mWay;
    private static String mMonth;
    private static String mDay;

    public static String getVersionCode() {
        int versionCode = 0;
        Context context = NewDTVApp.getApp().getApplicationContext();
        try {
            versionCode = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return Integer.toString(versionCode);
    }

    public static boolean hasNetwork(Context context) {
        NetworkInfo workinfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (workinfo == null || !workinfo.isAvailable()) {
            return false;
        }
        return true;
    }

    public static String getTimeNoInterval(String type) {
        Time t = new Time();
        t.setToNow();
        return (t.hour < 10 ? Constant.MOVIES_SEQUESE + t.hour : t.hour + "") + type + (t.minute < 10 ? Constant.MOVIES_SEQUESE + t.minute : t.minute + "");
    }

    public static String getSystemTime() {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }

    public static String getStringTime(String type) {
        String hour;
        String minute;
        String interval;
        Time t = new Time();
        t.setToNow();
        ContentResolver cv = NewDTVApp.getApp().getApplicationContext().getContentResolver();
        String strTimeFormat = System.getString(cv, "time_12_24");
        if (strTimeFormat == null) {
            System.putString(cv, "time_12_24", "24");
            strTimeFormat = "24";
        }
        if (strTimeFormat.equals("24")) {
            hour = t.hour < 10 ? Constant.MOVIES_SEQUESE + t.hour : t.hour + "";
            minute = t.minute < 10 ? Constant.MOVIES_SEQUESE + t.minute : t.minute + "";
            interval = "";
        } else {
            int hourtemp = t.hour <= 12 ? t.hour : t.hour - 12;
            hour = hourtemp < 10 ? Constant.MOVIES_SEQUESE + hourtemp : hourtemp + "";
            minute = t.minute < 10 ? Constant.MOVIES_SEQUESE + t.minute : t.minute + "";
            interval = t.hour < 12 ? " am" : " pm";
        }
        return hour + type + minute + interval;
    }

    public Utils() {
        super();
    }


    public static String StringData(){

        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
        if("1".equals(mWay)){
            mWay ="日";
        }else if("2".equals(mWay)){
            mWay ="一";
        }else if("3".equals(mWay)){
            mWay ="二";
        }else if("4".equals(mWay)){
            mWay ="三";
        }else if("5".equals(mWay)){
            mWay ="四";
        }else if("6".equals(mWay)){
            mWay ="五";
        }else if("7".equals(mWay)){
            mWay ="六";
        }
        return "周"+mWay;
    }

    public static String StringDate(){
        final Calendar c = Calendar.getInstance();
        mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// »ñÈ¡µ±Ç°ÔÂ·Ý
        mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// »ñÈ¡µ±Ç°ÔÂ·ÝµÄÈÕÆÚºÅÂë
        return  mMonth+"/"+mDay;
    }

    public static void showToast(Context context, String text, int image) {
        Long end = Long.valueOf(java.lang.System.currentTimeMillis());
        if (end.longValue() - start >= 1000 || !text.equals(mtext)) {
            start = end.longValue();
            View view = LayoutInflater.from(context).inflate(R.layout.tv_toast, null);
            ImageView iv_toast = (ImageView) view.findViewById(R.id.iv_smtv_toast);
            ((TextView) view.findViewById(R.id.tv_smtv_toast)).setText(text);
            iv_toast.setBackgroundResource(image);
            Toast toast = new Toast(context);
            toast.setView(view);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.show();
            mtext = text;
        }
    }

    public static void loadingShow_tv(Context context, int message) {
        if (Loadingdialog != null && Loadingdialog.isShowing()) {
            Loadingdialog.dismiss();
            Loadingdialog = null;
        }
        Loadingdialog = new LiveLoadingDialog(context, R.style.Exitdialog);
        Loadingdialog.setLoadingMsg(message);
        Loadingdialog.setCanceledOnTouchOutside(true);
        Loadingdialog.setCancelable(true);
        Loadingdialog.show();
    }

    public static void loadingClose_Tv() {
        if (Loadingdialog != null) {
            Loadingdialog.cancel();
            Loadingdialog = null;
        }
    }

    public static void Dialog_registerSN_Show(Context context, int message) {
        if (Loadingdialog != null && Loadingdialog.isShowing()) {
            Loadingdialog.dismiss();
        }
        Loadingdialog = new LiveLoadingDialog(context, R.style.Registerdialog);
        Loadingdialog.setLoadingMsg(message);
        Loadingdialog.setCanceledOnTouchOutside(true);
        Loadingdialog.setCancelable(true);
        Loadingdialog.show();
    }

    public static void Dialog_registerSN_Close() {
        if (Loadingdialog != null) {
            Loadingdialog.cancel();
            Loadingdialog = null;
        }
    }

    public static void loadingSearch_tv(Context context, int message) {
        if (context != null) {
            Log.d(TAG, "show() start");
            if (Loadingserachlog != null && Loadingserachlog.isShowing()) {
                Loadingserachlog.dismiss();
            }
            Loadingserachlog = new SearchLoadingDialog(context, R.style.Exitdialog);
            Loadingserachlog.setLoadingMsg(message);
            Loadingserachlog.setCanceledOnTouchOutside(false);
            Loadingserachlog.setCancelable(true);
            Loadingserachlog.show();
            Log.d(TAG, "show() end");
        } else {
            Log.d(TAG, "loadingSearch_tv context==null");
        }
    }

    public static void loadingSerchClose_Tv() {
        if (Loadingserachlog != null) {
            Loadingserachlog.cancel();
            Loadingserachlog = null;
        }
    }

    public static String matchString(String name) {
        Pattern p = Pattern.compile("[0-9]\\d*$");
        if (!TextUtils.isEmpty(name)) {
            Matcher m = p.matcher(name);
            if (m.find()) {
                return NewDTVApp.getApp().getApplicationContext().getResources().getString(R.string.set) + m.group() + NewDTVApp.getApp().getApplicationContext().getResources().getString(R.string.sets);
            }
        }
        return "";
    }

    public static String getVideogvDatas(String streamName, Boolean isList) {
        if (Pattern.compile("[0-9]\\d*$").matcher(streamName).find()) {
            if (TextUtils.isEmpty(streamName) || streamName.equals("")) {
                return null;
            }
            String Strame_name = streamName.substring(streamName.lastIndexOf("_") + 1);
            if (isList.booleanValue()) {
                return NewDTVApp.getApp().getApplicationContext().getResources().getString(R.string.set) + Strame_name + NewDTVApp.getApp().getApplicationContext().getResources().getString(R.string.date);
            }
            return NewDTVApp.getApp().getApplicationContext().getResources().getString(R.string.set) + Strame_name + NewDTVApp.getApp().getApplicationContext().getResources().getString(R.string.sets);
        } else if (TextUtils.isEmpty(streamName) || streamName.equals("")) {
            return null;
        } else {
            return streamName;
        }
    }

    public static void showExitToast(Context context, ViewGroup viewGroup) {
        View layout = LayoutInflater.from(context).inflate(R.layout.exit_toast, viewGroup);
        Toast toast = new Toast(context);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();
    }

    public static String localipget() {
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                Enumeration<InetAddress> enumIpAddr = ((NetworkInterface) en.nextElement()).getInetAddresses();
                while (enumIpAddr.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException e) {
        }
        return null;
    }

    public static String getPackageName(Context context, String strFile) {
        PackageInfo packageInfo = context.getPackageManager().getPackageArchiveInfo(strFile, PackageManager.GET_ACTIVITIES);
        if (packageInfo != null) {
            return packageInfo.applicationInfo.packageName;
        }
        return null;
    }

    public static String getApkName(Context context, String packageName) {
        String apkName = null;
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            if (packageInfo != null) {
                apkName = pm.getApplicationLabel(packageInfo.applicationInfo).toString();
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return apkName;
    }

    public static String getAppNameByApkFile(Context context, String apkFilePath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo packageInfo = pm.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES);
        if (packageInfo != null) {
            return pm.getApplicationLabel(packageInfo.applicationInfo).toString();
        }
        return null;
    }

    public static void toastDialog(Context context, String str) {
        try {
            if (!((Activity) context).isFinishing()) {
                if (reg_fail != null && reg_fail.isShowing()) {
                    reg_fail.dismiss();
                    reg_fail = null;
                }
                reg_fail = new ToastDialog(context, R.style.error_dialog_style);
                reg_fail.setCancelable(true);
                reg_fail.setCanceledOnTouchOutside(true);
                ((ToastDialog) reg_fail).setShowMsg(str);
                reg_fail.show();
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    public static Dialog getToastDialog() {
        return reg_fail;
    }

    public static void hideErrorDialog(Context context) {
        try {
            if (!((Activity) context).isFinishing() && reg_fail != null && reg_fail.isShowing()) {
                reg_fail.dismiss();
                reg_fail = null;
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    public static void hideErrorDialog() {
        try {
            if (reg_fail != null && reg_fail.isShowing()) {
                reg_fail.dismiss();
                reg_fail = null;
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    public static boolean isToastDialogShow() {
        try {
            if (reg_fail == null || !reg_fail.isShowing()) {
                return false;
            }
            return true;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e2) {
            e2.printStackTrace();
            return false;
        }
    }

    public static boolean isNumberic(String str) {
        return Pattern.compile("[0-9]*").matcher(str).matches();
    }

    public static String getLanguage(Context context) {
        if (context.getResources().getConfiguration().locale.getLanguage().endsWith("zh")) {
            return "zh";
        }
        return "en";
    }

    public static void addActivity(Activity activity) {
        mList.add(activity);
    }

    public static void exit() {
        for (Activity activity : mList) {
            if (activity != null) {
                activity.finish();
            }
        }
    }

    public static <T> boolean isObjEmpty(T obj) {
        return obj == null || obj.equals("");
    }

    public static <T> boolean isListEmpty(List<T> obj) {
        return obj == null || obj.size() <= 0;
    }

    public static String getPosterUrl(MovieDetail movieDetail) {
        if(movieDetail!=null) {
            List<PhotoInfo> photoInfos = movieDetail.getPhotos();
            if(photoInfos!=null&&photoInfos.size()>0) {
                for (int i=0;i<photoInfos.size();i++) {
                    if(photoInfos.get(i).getMedia_type().equals("poster")) {
                        if(photoInfos.get(i).getMedia_url()!=null) {
                            return Constants.API_ROOT()+photoInfos.get(i).getMedia_url();
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        return null;
    }

    public static String getBannerUrl(MovieDetail movieDetail) {
        if(movieDetail!=null) {
            List<PhotoInfo> photoInfos = movieDetail.getPhotos();
            if(photoInfos!=null&&photoInfos.size()>0) {
                for (int i=0;i<photoInfos.size();i++) {
                    if(photoInfos.get(i).getMedia_type().equals("banner")) {
                        if(photoInfos.get(i).getMedia_url()!=null) {
                            return Constants.API_ROOT()+photoInfos.get(i).getMedia_url();
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        return null;
    }

    public static boolean isMuted(AudioManager am) {
        boolean isMuted =false;
        try {
            Method m = AudioManager.class.getMethod("isStreamMute", int.class);
            try {
                isMuted = (Boolean) m.invoke(am, AudioManager.STREAM_MUSIC);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            java.lang.System.out.println(e);
        }
        return isMuted;
    }
}
